package com.king.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.king.mapper.BorrowBooksMapper;
import com.king.model.common.RestResponse;
import com.king.model.dto.BorrowBooksDto;
import com.king.model.dto.BorrowBooksParams;
import com.king.model.common.PageParams;
import com.king.model.common.PageResult;
import com.king.model.po.BorrowBooks;
import com.king.service.BorrowBooksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author king
 */
@Slf4j
@Service
public class BorrowBooksServiceImpl extends ServiceImpl<BorrowBooksMapper, BorrowBooks> implements BorrowBooksService {

    @Autowired
    private BorrowBooksMapper borrowBooksMapper;

    @Override
    public PageResult<BorrowBooksDto> getBorrowBooks(@RequestParam(required = false) BorrowBooksParams borrowBooksParams, PageParams pageParams) {
        pageParams.setPageNo((pageParams.getPageNo()-1) * pageParams.getPageSize());
        List<BorrowBooksDto> borrowBooks = borrowBooksMapper.getBorrowBooks(pageParams, borrowBooksParams);
        Long borrowBooksCounts = borrowBooksMapper.getBorrowBooksCounts(borrowBooksParams);

        return new PageResult<BorrowBooksDto>(borrowBooks, borrowBooksCounts, pageParams.getPageNo(), borrowBooks.size());
    }

    @Override
    public RestResponse<Boolean> borrow(Integer id, Integer userId) {
        BorrowBooks borrowBooks = new BorrowBooks();
        borrowBooks.setBookId(id);
        borrowBooks.setBorrowTime(LocalDateTime.now());
        borrowBooks.setUserId(userId);
        borrowBooks.setStatus(false);
        boolean flag = save(borrowBooks);
        if (flag){
            return RestResponse.success(true);
        }
        return RestResponse.fail("借阅失败");
    }

    @Override
    public RestResponse<Boolean> returnBook(Integer borrowId) {
        BorrowBooks borrowBooks = new BorrowBooks();
        borrowBooks.setId(borrowId);
        borrowBooks.setStatus(true);
        borrowBooks.setReturnTime(LocalDateTime.now());
        boolean flag = updateById(borrowBooks);
        if (flag){
            return RestResponse.success(true);
        }
        return RestResponse.fail("归还失败");
    }
}
